package net.zjitc.utils.db;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by Administrator on 2017/11/9.
 */
public class C3P0Utils {
    public static DataSource dataSource=null;

    //ThreadLocal为每个使用该变量的线程提供独立的变量副本
    public static ThreadLocal<Connection> th = new ThreadLocal<Connection>();

    static
    {
        dataSource=new ComboPooledDataSource();
    }
    public static DataSource getDataSource()
    {
        return dataSource;
    }
    //开启一个事务
    public static Connection getConnection() throws SQLException {
        Connection connection = th.get();
        if (connection!=null){
            return connection;//带事务的连接
        }
        return dataSource.getConnection();//此连接不带事务
    }

    //开启一个事务
    public static void startTransation() throws SQLException {
        Connection connection = th.get();
        if (connection!=null){
            throw new RuntimeException("事务已经开启，不需要再开启");
        }
        //获得一个连接，并存在th里面
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        th.set(connection);
    }

    //提交事务
    public static void commitTransation() throws SQLException {
        Connection connection = th.get();
        if (connection==null){
            throw new RuntimeException("本身没有事务，无法提交");
        }
        connection.commit();
        connection.close();
        connection = null;
        th.remove();//清除
    }

    //回滚操作
    public static void rollbackTransatin() throws SQLException {
        Connection connection = th.get();
        if (connection==null){
            throw  new RuntimeException("本身没有事务，无法回滚");
        }
        connection.rollback();
        connection.close();
        connection = null;
        th.remove();
    }

    //关闭
    public static void closeConnection(Connection connection) throws SQLException {
        Connection connection1 = th.get();
        if (connection1!=connection){//只关闭普通的连接，带事务的连接在提交或回滚的时候关闭
            connection.close();
        }
    }
}
